import { MongodbMoudle } from "mx-database";
import { ifBase, Tables, ifKeepKeyUnit, ifKeepImageUnit } from './base';
// TeMongoDB.registTable(Tables.user, {
//     "mail": {
//         "type": "String",
//         "Required": true
//     },
//     "key": "String",
//     "count": "Number",
//     "time": "Date"
// });
// TeMongoDB.registTable(Tables.tinypic, {
//     "srcmd5": {
//         "type": "String",
//         "Required": true
//     },
//     "name": "String",
//     "tinymd5": "String",
//     "time": "Date",
//     "pic": "Buffer"
// });
export class MongoDBMode implements ifBase {
    databaseName: string = ""
    async init(mongoIp: string, mongoPort: string, mongoDb: string) {
        this.databaseName = mongoDb;
        return true
    }

    async save(this: ifKeepImageUnit, key: string, n: any, ...args: any): Promise<any> {
        let saveArgs = arguments;

        let db = await MongodbMoudle.get_database(this.database).get_unit(Tables.tinypic, { 'srcmd5': this.srcmd5 }).load()
        for (let i = 0; i < saveArgs.length; i = i + 2) {
            db.set(saveArgs[i], saveArgs[i + 1]);
        }

        return db.force_save()
    }

    removeSelf(this: ifKeepImageUnit) {
        return MongodbMoudle.get_database(this.database).del(Tables.tinypic, { 'srcmd5': this.srcmd5 });
    }
    async getPic(f: any) {
        let db = await MongodbMoudle.get_database(this.databaseName).get_unit(Tables.tinypic, f).load();
        if (db.empty) {
            return undefined;
        }
        return {
            tinyMd5: db.get('tinyMd5') as string,
            srcmd5: db.get('srcmd5') as string,
            pic: db.get('pic').buffer,
            name: db.get('name') as string,
            time: db.get('time') as number,
            database: this.databaseName,
            save: this.save,
            removeSelf: this.removeSelf,
        }
    }

    async inserPic(info: any) {

        let db = await MongodbMoudle.get_database(this.databaseName).get_unit(Tables.tinypic, { srcmd5: info.srcmd5 }).load();
        if (db.empty) {
            db.insert(info)
        }
        else {
            for (let key in info) {
                if (key == 'srcmd5') continue;
                db.set(key, info[key]);
            }
        }
    }

    freshAllDB() {
        return new Promise<boolean>(function (r) {
            setTimeout(function () {
                r(true)
            }, 1000)
        })
    }
}
